<!-- filename: pages/public-playlists/public-playlists.vue (最终重构版) -->
<template>
  <view class="page-container">
    <Header @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <div class="content-wrapper" style="padding-top: 60px;">
      <!-- 【重构1】使用与 playlist.vue 完全一致的 header 结构 -->
      <header class="page-header">
        <div class="header-left">
          <h1 class="page-title">全部精选歌单</h1>
          <span class="item-count">{{ `共 ${pagination.total_items} 个` }}</span>
        </div>
      </header>
      
      <SearchBar 
        ref="searchBarRef" 
        @search="handleSearch"
        search-context="playlist_global" 
      />
      
      <ListControls
        :pagination="pagination"
        :current-sort="currentSort"
        context="public-playlists"
        @update:page="handlePageChange"
        @update:sort="handleSortChange"
      />

      <main class="list-container">
        <view v-if="isLoading" class="loading-state">加载中...</view>
        <view v-else-if="playlists.length === 0" class="empty-state">暂无公共歌单</view>
        
        <!-- 【重构2】使用与 playlist.vue 完全一致的网格和卡片结构 -->
        <view v-else class="playlist-grid">
          <view 
            v-for="p in playlists" 
            :key="p.id" 
            class="public-playlist-card"
          >
            <!-- 分享按钮 -->
            <view class="share-btn" @click.stop="handleShare(p.id, p.name)">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3z"/></svg>
            </view>
            <!-- Clone 按钮 -->
            <view class="clone-btn" @click.stop="handleClonePlaylist(p.id)">
               <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M14.47 13.53L12.04 11.1l2.43-2.43-1.41-1.41-2.43 2.43-1.29-1.29-.71.71 1.29 1.29-2.43 2.43 1.41 1.41 2.43-2.43 1.29 1.29.71-.71-1.29-1.29zM19 3h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7-.25c.41 0 .75.34.75.75s-.34.75-.75.75-.75-.34-.75-.75.34-.75.75-.75zM19 19H5V5h14v14z"/></svg>
            </view>

            <view class="cover-wrapper" @click="navigateToPublicDetail(p.id)">
              <image v-if="p.cover_url" :src="p.cover_url" class="cover-image" mode="aspectFill" />
              <view v-else class="cover-placeholder music-icon">
                <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/></svg>
              </view>
            </view>
            <view class="playlist-info" @click="navigateToPublicDetail(p.id)">
              <text class="playlist-name">{{ p.name }}</text>
              <text class="creator-name">by {{ p.username }}</text>
            </view>
          </view>
        </view>
      </main>
    </div>

    <Player v-if="playerStore.showPlayer" />
  </view>
</template>


<script setup>
import { reactive, ref } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { usePlayerStore } from '@/store/player';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import Player from '@/components/Player.vue';
import SearchBar from '@/components/SearchBar/SearchBar.vue';
import ListControls from '@/components/ListControls/ListControls.vue';

const authStore = useAuthStore();
const playerStore = usePlayerStore();
const isAuthModalVisible = ref(false);

const playlists = ref([]);
const allPlaylistsForSearch = ref([]);
const isLoading = ref(true);
const isFetchingMore = ref(false);

const pagination = reactive({
  current_page: 1,
  total_pages: 1,
  total_items: 0,
});
const currentSort = ref('latest');
const searchQuery = ref('');

// --- 【核心修改2】重写 API 请求函数 ---

const fetchPublicPlaylists = async (isInitialLoad = false) => {
  if (isInitialLoad) {
    isLoading.value = true;
    playlists.value = [];
    allPlaylistsForSearch.value = [];
    pagination.current_page = 1;
  } else {
    isFetchingMore.value = true;
  }

  const params = new URLSearchParams({
    page: pagination.current_page,
    sort_by: currentSort.value,
    limit: 12,
  });

  try {
    const data = await request({
      url: `/api/public/playlists?${params.toString()}`,
      method: 'GET'
    });
    if (data && data.playlists) {
      const fetched = data.playlists;
      if (isInitialLoad) {
        playlists.value = fetched;
      } else {
        playlists.value.push(...fetched);
      }
      allPlaylistsForSearch.value = [...playlists.value];
      Object.assign(pagination, data.pagination);
    }
  } catch (error) {
    console.error("Failed to fetch public playlists:", error);
  } finally {
    isLoading.value = false;
    isFetchingMore.value = false;
  }
};

const handleClonePlaylist = (playlistId) => {
  if (!authStore.isLoggedIn) {
    isAuthModalVisible.value = true;
    return;
  }
  uni.showModal({
    title: '确认克隆',
    content: '是否要将此歌单复制一份到您的“我的歌单”中？',
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '正在复制...' });
        try {
          await request({
            url: `/api/public/playlists/${playlistId}/clone`,
            method: 'POST',
          });
          uni.showToast({ title: '已复制到我的歌单', icon: 'success' });
        } catch (error) {
          const errorMsg = error?.data?.error || '复制失败';
          uni.showToast({ title: errorMsg, icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};


// --- 无需修改的函数 ---
onLoad(() => {
  fetchPublicPlaylists(true);
});

onReachBottom(() => {
  if (pagination.current_page < pagination.total_pages && !isFetchingMore.value) {
    pagination.current_page++;
    fetchPublicPlaylists(false);
  }
});

const handleSearch = (payload) => {
  searchQuery.value = payload.value.trim().toLowerCase();
  if (!searchQuery.value) {
    playlists.value = [...allPlaylistsForSearch.value];
  } else {
    playlists.value = allPlaylistsForSearch.value.filter(p => 
      p.name.toLowerCase().includes(searchQuery.value) || 
      p.username.toLowerCase().includes(searchQuery.value)
    );
  }
};

const handleSortChange = (newSort) => {
  currentSort.value = newSort;
  fetchPublicPlaylists(true);
};

const handlePageChange = () => {};

const navigateToPublicDetail = (id) => {
  uni.navigateTo({
    url: `/pages/public-playlist-detail/public-playlist-detail?id=${id}`
  });
};

const handleShare = async (playlistId, playlistName) => {
  const url = `${window.location.origin}/#/pages/public-playlist-detail/public-playlist-detail?id=${playlistId}`;
  const shareData = {
    title: `分享歌单: ${playlistName || '精选歌单'}`,
    text: `快来听听《${playlistName || '精选歌单'}》`,
    url: url,
  };
  if (navigator.share) {
    try {
      await navigator.share(shareData);
    } catch (err) {
      if (err.name !== 'AbortError') console.error("分享失败:", err);
    }
  } else {
    try {
      await navigator.clipboard.writeText(url);
      uni.showToast({ title: "分享链接已复制到剪贴板", icon: "none" });
    } catch (err) {
      uni.showToast({ title: "复制链接失败", icon: "error" });
    }
  }
};
</script>

<style scoped lang="scss">
/* --- 页面布局 --- */
.page-container {
  display: flex;
  justify-content: center; /* 让 content-wrapper 水平居中 */
  width: 100%;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.content-wrapper {
  width: 100%;
  max-width: 800px; /* 关键：限制最大宽度，与播放器对齐 */
  background-color: #ffffff;
  padding: 20px;
  padding-bottom: 150px;
}

/* --- 【核心修正1】Header 样式调整 --- */
.page-header {
  display: flex;
  align-items: baseline; /* 基线对齐，让大字体和小字体底部对齐 */
  padding-top: 20px; /* 增加与顶部 Header 的距离 */
  margin-bottom: 20px;
}
.header-left {
  display: flex;
  align-items: baseline;
  gap: 15px; /* 在标题和数量之间增加间距 */
}
.page-title {
  font-size: 28px;
  font-weight: bold;
}
.item-count {
  font-size: 16px;
  color: #888;
  padding-bottom: 3px; /* 微调，让其与大标题更协调 */
}

/* --- 排序控件与列表的间距 --- */
.list-container {
  margin-top: 20px;
}
.loading-state, .empty-state {
  text-align: center;
  color: #888;
  padding: 50px 0;
}

/* --- 网格和卡片样式 (保持不变) --- */
.playlist-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
}
.public-playlist-card {
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    .share-btn, .clone-btn { opacity: 1; }
  }
  @media (hover: none) {
    .share-btn, .clone-btn { opacity: 1; }
  }
}
.share-btn, .clone-btn {
  position: absolute; top: 8px;
  width: 28px; height: 28px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  z-index: 2; opacity: 0; transition: opacity 0.2s;
  cursor: pointer; color: white;
  background-color: rgba(0, 122, 255, 0.8);
}
.share-btn { right: 8px; }
.clone-btn { left: 8px; }
.cover-wrapper {
  width: 100%; padding-top: 100%; position: relative; background-color: #f0f0f0;
}
.cover-image {
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
}
.cover-placeholder.music-icon {
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
  display: flex; align-items: center; justify-content: center;
  svg { color: #aaa; }
}
.playlist-info {
  padding: 15px;
}
.playlist-name {
  display: block; font-weight: 500; font-size: 16px; color: #333;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.creator-name {
  display: block; font-size: 12px; color: #888; margin-top: 5px;
}
</style>